/*
 * @Author: wangtao
 * @Date: 2020-11-09 10:48:23
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-07-13 14:37:44
 * @Description: 修改回单
 */
import React from 'react';
import {
  View,
  StyleSheet,
  ScrollView,
  NativeModules,
  Keyboard,
} from 'react-native';
import {
  mainBgColorLightGray,
  px2dp,
} from '@/styles';
import { Button, msg } from '@/common';
import api from '@/api';

import { uploadImage } from '@/config';
import ReceiptItem from './components/receipt-item';

const { Submit } = Button;

export default class ReceiptEdit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {}, // 运单信息
      routerFrom: '',
      keyboardHeight: 0, // 键盘高度
      dataList: [], // 请求的返回的data list
      unitOptionsObj: {}, // 单位对象map
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { data, routerFrom, transportNo } = params;
    console.log('🚀🚀🚀wimi======>>>routerFrom', routerFrom);
    this.setState({ data, routerFrom, transportNo });
    this.getWayBillPics(transportNo);
    this.getUnitList();

    // 监听键盘
    this.keyboardDidShowListener = Keyboard.addListener(
      'keyboardWillShow',
      this._keyboardDidShow.bind(this),
    );
    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardWillHide',
      this._keyboardDidHide.bind(this),
    );
  }

  render() {
    const { dataList, keyboardHeight, unitOptionsObj } = this.state;
    console.log('zeki======>>>dataList', dataList);
    return (
      <View style={styles.container}>
        <ScrollView
          showsVerticalScrollIndicator={false}
          contentContainerStyle={{ paddingBottom: px2dp(250 + keyboardHeight) }}
        >
          {/* 装货 */}
          {dataList &&
            dataList.map((item, index) => {
              if (item.type === 1) {
                return (
                  <ReceiptItem
                    type='loading'
                    isWeighing={item.isWeighing}
                    itemIndex={index}
                    addressDetails={item.addr}
                    weightUnit={item.weightUnit}
                    selectImg={(key, detailsIndex, itemIndex) =>
                      this.selectImg(key, detailsIndex, itemIndex, 'loading')}
                    onChange={(key, val, detailsIndex, itemIndex) =>
                      this.onChange(
                        key,
                        val,
                        detailsIndex,
                        itemIndex,
                        'loading',
                      )}
                    addCard={(itemIndex, type) =>
                      this.addCard(itemIndex, 'loading')}
                    deleteCard={(detailsIndex, itemIndex) =>
                      this.deleteCard(detailsIndex, itemIndex, 'loading')}
                    details={item.details || [{}]}
                    unitOptionsObj={unitOptionsObj}
                  />
                );
              }
              if (item.type === 2) {
                return (
                  <ReceiptItem
                    type='unloading'
                    isWeighing={item.isWeighing}
                    itemIndex={index}
                    addressDetails={item.addr}
                    weightUnit={item.weightUnit}
                    selectImg={(key, detailsIndex, itemIndex) =>
                      this.selectImg(key, detailsIndex, itemIndex, 'unloading')}
                    addCard={(itemIndex) =>
                      this.addCard(itemIndex, 'unloading')}
                    deleteCard={(detailsIndex, itemIndex) =>
                      this.deleteCard(detailsIndex, itemIndex, 'unloading')}
                    onChange={(key, val, detailsIndex, itemIndex) =>
                      this.onChange(
                        key,
                        val,
                        detailsIndex,
                        itemIndex,
                        'unloading',
                      )}
                    details={item.details || [{}]}
                    unitOptionsObj={unitOptionsObj}
                  />
                );
              }
            })}
        </ScrollView>
        <Submit
          text='提交'
          boxStyle={{
            width: px2dp(640),
            height: px2dp(96),
            borderRadius: px2dp(48),
            overflow: 'hidden',
            position: 'absolute',
            bottom: px2dp(100),
          }}
          btnStyle={{}}
          btnTextStyle={{
            fontSize: px2dp(36),
          }}
          onClick={() => {
            this.submit();
          }}
        />
      </View>
    );
  }

  // 获取回单详情
  getWayBillPics = (transportNo) => {
    let params = {
      transportNo,
    };
    api.supply.getAllTicks(params).then((res) => {
      if (res.success) {
        this.setState({ dataList: res.data });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  // 获取单位
  getUnitList = () => {
    return new Promise((resolve) => {
      api.supply.unitList().then((res) => {
        this.setState({ unitList: res.data }, () => {
          resolve(res);
        });
      });
    });
  };

  // 提交
  submit = () => {
    const { dataList, routerFrom } = this.state;
    const params = dataList;
    // 校验
    const whetherInPut = (weightUnit, isWeighing) => {
      if (weightUnit == 'ton' || weightUnit == 'kg') {
        // 判断isWeighing字段是否存在(以前的订单没有这个字段)
        // 不存在：按之前的业务逻辑单位为ton或者kg则填写 否则不填
        // 存在：1 需要过磅 2 不需过磅； 需要过磅则填写 不需要过磅判断单位 ton或者kg则填写 否则不填
        if (!isWeighing) {
          return true;
        } if (isWeighing == 1) {
          return true;
        } if (isWeighing == 2) {
          return false;
        }
      }
      return false;
    };

    // 当满足其中单位时候填写或展示
    let weightList = ['ton', 'kg', 'piece', 'square'];

    // 单位翻译
    let weightUnitText = {
      ton: '净重',
      kg: '净重',
      piece: '件数',
      square: '方数',
    };

    // 回单类型翻译
    let detailType = {
      1: '发货单',
      2: '收货单'
    };

    // 校验 list
    for (let i = 0; i < dataList.length; i++) {
      const { details, weightUnit, type, isWeighing } = dataList[i];
      if (details && details.length > 0) {
        for (let index = 0; index < details.length; index++) {
          const { fileUrl, roughWeight, tarWeight, netWeight } = details[index];
          if (!fileUrl) { // 是否上传了图片
            msg.emit('app:tip', { text: `${detailType[type]}第${index + 1}单票据必传` });
            return;
          }

          if (whetherInPut(weightUnit, isWeighing) && !roughWeight) {
            msg.emit('app:tip', { text: `${detailType[type]}第${index + 1}单毛重必传` });
            return;
          }

          if (whetherInPut(weightUnit, isWeighing) && !tarWeight) {
            msg.emit('app:tip', { text: `${detailType[type]}第${index + 1}单皮重必传` });
            return;
          }

          if (weightList.includes(weightUnit) && !whetherInPut(weightUnit, isWeighing) && !netWeight) {
            msg.emit('app:tip', { text: `${detailType[type]}第${index + 1}单${weightUnitText[weightUnit]}必传` });
            return;
          }
        }
      }
    }

    api.supply.editWayBillPics(params).then((res) => {
      if (res.success) {
        msg.emit('app:tip', { text: '提交成功' });
        msg.emit('router: refreshRoute', {
          routeName: 'DriverTab',
        });
        msg.emit('router: goToNext', { routeName: routerFrom });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  // 选择照片
  selectImg = (key, detailsIndex, itemIndex, type) => {
    NativeModules.DataModule.chooseImage((path, imageBase64) => {
      this.upload(path, key, detailsIndex, itemIndex, type);
    });
  };

  // 上传照片
  upload(path, key, detailsIndex, itemIndex, type) {
    console.log('🚀🚀🚀wimi======>>>path', path);
    NativeModules.WindowModule.showLoading();
    uploadImage('upload?dirName=carWl', path)
      .then((res) => {
        console.log(`uploadImage：${JSON.stringify(res)}`);
        // 请求成功
        if (res.success) {
          this.onChange(key, res.data.localId, detailsIndex, itemIndex, type);
        } else {
          NativeModules.WindowModule.showWindow(
            { content: '上传失败，请重试', onlyRightBtn: '1' },
            (e) => {},
          );
          // 服务器返回异常，设定服务器返回的异常信息保存在 header.msgArray[0].desc
          console.log('--->', res.header.msgArray[0].desc);
        }
        NativeModules.WindowModule.dismissLoading();
      })
      .catch((err) => {
        console.log(err);
        NativeModules.WindowModule.dismissLoading();
        // 请求失败
        NativeModules.WindowModule.showWindow(
          { content: '上传出错，请重试', onlyRightBtn: '1' },
          (e) => {},
        );
      });
  }

  // onChange
  onChange = (key, val, detailsIndex, itemIndex, type) => {
    // 如果是装货
    let { dataList } = this.state;
    dataList[itemIndex].details[detailsIndex][key] = val;
    this.setState({ dataList });
  };

  // 新增卡片
  addCard = (itemIndex, type) => {
    let { dataList } = this.state;
    if (dataList[itemIndex].details.length >= 10) {
      msg.emit('app:tip', { text: '最多上传10张回单' });
      return;
    }
    dataList[itemIndex].details.push({});
    this.setState({ dataList });
  };

  // 删除卡片
  deleteCard = (detailsIndex, itemIndex, type) => {
    let { dataList } = this.state;
    dataList[itemIndex].details.splice(detailsIndex, 1);
    this.setState({ dataList });
  };

  _keyboardDidShow(e) {
    this.setState({
      keyboardHeight: e.startCoordinates.height,
    });
  }

  _keyboardDidHide(e) {
    this.setState({
      keyboardHeight: 0,
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    alignItems: 'center',
  },
});
